/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bean.session;

import entity.DataObjectEntity;
import entity.PersonEntity;
import entity.SalesLeadEntity;
import java.util.List;
import javax.ejb.Stateless;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Root;

/**
 *
 * @author wei
 */
@Stateless
public class SalesLeadEntityFacade extends AbstractFacade<SalesLeadEntity> {

    @PersistenceContext(unitName = "MacTeam-warPU")
    private EntityManager em;

    protected EntityManager getEntityManager() {
        return em;
    }

    public SalesLeadEntityFacade() {
        super(SalesLeadEntity.class);
    }

    public DataModel findAllSalesLead() {
        Query query = em.createQuery("SELECT S FROM SalesLead S");
        return new ListDataModel(query.getResultList());
    }

//    public DataModel findSalesLead(String userInput, String searchField) {
//        Query query = em.createQuery("SELECT S FROM SalesLead S"+ " WHERE S."+""+searchField+""+" like "+"'%"+userInput+"%'");
//        return new ListDataModel(query.getResultList());
//    }
//       public DataModel findSalesLead(String userInput, String searchField) {
//        Query query = em.createQuery("SELECT S FROM SalesLead S"+ " WHERE S."+""+searchField+""+" = "+"'"+userInput+"'");
//        return new ListDataModel(query.getResultList());
    public DataModel findSalesLead(String userInput, String searchField) {

        if (!(searchField.equals("createdBy"))) {
            Query query = em.createQuery("SELECT S FROM SalesLead S" + " WHERE S." + "" + searchField + "" + " like " + "'%" + userInput + "%'");
            return new ListDataModel(query.getResultList());
        } 
        
        else {
            CriteriaBuilder builder = getEntityManager().getCriteriaBuilder();
            javax.persistence.criteria.CriteriaQuery cq = builder.createQuery();
            Root<DataObjectEntity> salesLeadRoot = cq.from(SalesLeadEntity.class);
            //Root<PersonEntity> personRoot = cq.from(PersonEntity.class);
            cq.select(salesLeadRoot);

            cq.where(builder.equal(salesLeadRoot.get("createdBy").get("id"), userInput));

            //cq.where(customerRoot.get("customerAccount").get("createdBy").get("id").isNull());
            System.out.println(cq.toString());
            return new ListDataModel(getEntityManager().createQuery(cq).getResultList());
        }
    }
      public List<SalesLeadEntity> getLockedUser(){
     Query query = (Query) em.createQuery("Select s from SalesLead s WHERE s.locked=true");
         List<SalesLeadEntity> list = (List<SalesLeadEntity>) query.getResultList();
        return list;
}
}
